<script>
import { v4 as uuidv4 } from "uuid";
export default {
  name: "MenDianComponent",
  data() {
    return {
      users: [],
      // 分页
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tableData: [], //表单数据对象
      // 弹出框的管理员选择
      options: [
        {
          value: "1",
          label: "管理员",
        },
        {
          value: "2",
          label: "咨询师",
        },
        {
          value: "3",
          label: "普通用户",
        },
      ],
      //图片
      imageUrl: [],
      acceptData: "",
      fileName: "",
      currentFile: {},
      //上架区域的字
      span: ["全部门店", "上架中", "已下架"],
      spanColor: "black",
      CurrentIndex: -1,

      //对话框的数据模型
      dialogFormVisible: false,
      formLabelWidth: "120px", //输入框标题宽度
      from: {
        //  新增数据
        id: "",
        username: "", //用户名（唯一）
        password: "", //密码
        nickname: "", //昵称
        email: "", //邮箱
        phone: "", //手机号
        role: "", //身份信息
        roleDescription:"",
        // 上边是新加的
        //经纬度坐标
        mode: 1, //1增加  2修改
      },
      timerId: null,
      //行数据
      index: "",
      row: {},
      //搜索框数据对象
      searchContent: {
        username: " ",
        nickname: " ",
        page: 1,
        size: 10,
      },
    };
  },
  methods: {
    // 删除
    handleDelete(id) {
      this.axios
        .delete("http://localhost:8080/user", {
          params: {
            id: id,
          },
        })
        .then((res) => {
          console.log("删除成功");
          console.log(res);
          // 删除成功后调用 flushTable 方法刷新表格
          this.flushTable();
        })
        .catch((err) => {});
      this.flushTable;
    },
    //新增门店
    addShop() {
      this.clearFrom()
      this.dialogFormVisible = true;
    },
    //新增门店
    //将想要新增的数据发送请求
    putFrom() {
      if (this.from.mode === 1) {
        this.axios
          .post("http://localhost:8080/user/update", {
              username: this.from.username, //用户名（唯一）
              password: this.from.password, //密码
              nickname: this.from.nickname, //昵称
              email: this.from.email, //邮箱
              phone: this.from.phone, //手机号
              role: this.from.role, //身份信息
          })
          .then((response) => {
            // this.flushTable();
            // this.clearFrom;
            // console.log(response);
            // this.initDialog(row);
            this.dialogFormVisible = false;
          })
          .catch((err) => {
            console.log("请求失败");
          });
        //后台处理需要时间，直接刷新可能获取不到最新的数据
        this.timerId = setTimeout(this.flushTable, 500);
      } else if (this.from.mode === 2) {
        console.log("啊实打实的撒"+this.from);
        
        //修改
        console.log(this.from);
        
        this.axios.put("/user", {
            id: this.from.id,
            username: this.from.username, //用户名（唯一）
            password: this.from.password, //密码
            nickname: this.from.nickname, //昵称
            email: this.from.email, //邮箱
            phone: this.from.phone, //手机号
            role: this.from.originalRole, //身份信息
          })
          .then((response) => {
            console.log(response);
            this.dialogFormVisible = false;
          })
          .catch((err) => {
            console.log("修改失败");
          });
        //后台处理需要时间，直接刷新可能获取不到最新的数据
        this.timerId = setTimeout(this.flushTable, 500);
        this.clearFrom();
        this.dialogFormVisible = false;
        this.from.mode = 1;
      }
    },
    //清空对话框数据
    clearFrom() {
      this.from.username = "";
      this.from.password = "";
      this.from.nickname = "";
      this.from.email = "";
      this.from.phone = "";
      this.from.role = "请选择权限";
    },
    //修改
    handleEdit(index, row) {
      console.log(row.role);
      this.index = index;
      this.row = row;
      this.from.mode = 2;
      this.initDialog(row);
      this.dialogFormVisible = true;
    },

    //初始化对话框
    initDialog(row) {
      this.from.id = row.id;
      this.from.username = row.username;
      this.from.password = row.password;
      this.from.nickname = row.nickname;
      this.from.email = row.email;
      this.from.phone = row.phone;
      this.from.originalRole = row.role;
      
      const roleMap = {
        1: "管理员",
        2: "咨询师",
        3: "普通用户",
      };
      this.from.roleDescription = roleMap[row.role] || "请选择权限";
      // 为了保持与原代码一致，我们仍然设置 this.from.role 为描述文本
      this.from.role = this.from.roleDescription;
  
  console.log('初始化后的 from 对象:', this.from);
      
    },
    

    //搜索框点击发送请求函数

    // 模糊搜索
    searchClick() {
      console.log("搜索参数:", this.searchContent);

      this.axios
        .get("http://localhost:8080/user/condition", {
          params: {
            page: this.pageNum,
            size: this.pageSize,
            username: this.searchContent.username.trim() || undefined,
            nickname: this.searchContent.nickname.trim() || undefined,
          },
        })
        .then((res) => {
          console.log("完整响应:", res);
          console.log("搜索响应数据:", res.data);

          if (res.data && res.data.code === 200) {
            // 假设后端返回的数据结构是 { code: 200, data: { list: [...], total: 100 } }
            this.tableData = res.data.data.list || [];
            this.total = res.data.data.total || 0;

            if (this.tableData.length === 0) {
              this.$message.info("没有找到匹配的记录");
            }
          } else {
            this.$message.error(res.data?.msg || "搜索失败");
          }
        })
        .catch((error) => {
          console.error("请求出错:", error);
          this.$message.error("获取数据失败，请稍后重试");
        });
    },
    //获取初始化表格数据
    flushTable() {
      this.axios
        .get("http://localhost:8080/user", {
          params: {
            page: this.pageNum,
            size: this.pageSize,
          },
        })
        .then((res) => {
          //处理响应数据
          console.log(res);
          // //真正需要的数据
          // //将得到的数据加载到tableData
          this.tableData = res.data.data.list;
          this.total = res.data.data.total;
        })
        .catch((err) => {});
    },
    // 分页
    handleSizeChange(size) {
      this.pageSize = size;
      // 可以在这里重新获取数据
      this.flushTable();
    },
    // 切换当前页
    handleCurrentChange(page) {
      console.log(page);
      this.pageNum = page;
      this.flushTable();
    },
  },
  created() {
    //初始化获得表格数据
    this.flushTable();
  },
};
</script>

<template>
  <div class="mendian">
    <div class="artistic-header">用户管理</div>
    <!--  上架-->
    <div class="sj">
      <!-- <span
        v-for="(v, i) in span"
        :key="v"
        :class="{ active: i === CurrentIndex }"
        @click="CurrentIndex = i"
        >{{ v }}</span
      > -->
    </div>
    <!-- 搜索框 -->
    <div class="searchAndDate cf">
      <div class="search">
        <span>用户名：</span>
        <el-input
          v-model="searchContent.username"
          placeholder="请输入内容"
          class="searchInputSize"
        ></el-input>
      </div>
      <div class="search">
        <span>昵称：</span>
        <el-input
          v-model="searchContent.nickname"
          placeholder="请输入内容"
          class="searchInputSize"
        ></el-input>
      </div>
      <el-button type="primary" icon="el-icon-search" @click="searchClick"
        >搜索</el-button
      >
    </div>
    <!--  增加    -->
    <el-button type="primary" @click="addShop" class="addTo"
      >添加用户</el-button
    >
    <el-dialog title="新增用户" :visible.sync="dialogFormVisible">
      <el-form :model="from">
        <!--    账户    -->
        <el-form-item label="账户：" :label-width="formLabelWidth">
          <el-input v-model="from.username" autocomplete="off"></el-input>
        </el-form-item>
        <!--    密码    -->
        <el-form-item label="密码：" :label-width="formLabelWidth">
          <el-input
            v-model="from.password"
            autocomplete="off"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>
        <!--   昵称   -->
        <el-form-item label="昵称：" :label-width="formLabelWidth">
          <el-input v-model="from.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <!--   邮箱    -->
        <el-form-item label="邮箱：" :label-width="formLabelWidth">
          <el-input v-model="from.email" autocomplete="off"></el-input>
        </el-form-item>
        <!--  手机号  -->
        <el-form-item label="手机号：" :label-width="formLabelWidth">
          <el-input v-model="from.phone" autocomplete="off"></el-input>
          <!--  测试详细地址取值-->
          {{ from.shopAddress }}
        </el-form-item>
        <!--      权限设置 -->
        <el-form-item label="权限设置：" :label-width="formLabelWidth">
          <el-select v-model="from.role" placeholder="请选择权限">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="putFrom">确 定</el-button>
      </div>
    </el-dialog>

    <!--  表格-->
    <div class="formTable">
      <el-table
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{
          'text-align': 'center',
          backgroundColor: '#1890ff',
          color: '#fff',
        }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column prop="username" label="用户名" width="180">
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="phone" label="手机号"> </el-table-column>
        <el-table-column prop="role" label="身份信息">
          <template slot-scope="scope">
            {{
              scope.row.role === 1
                ? "管理员"
                : scope.row.role === 2
                ? "咨询师"
                : "普通用户"
            }}
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              >修改信息</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--  分页-->
    <div class="block">
      <!-- <el-pagination
        layout="prev, pager, next"
        :total="page.total"
        :page-size="page.pageSize"
        :current-page="page.currentPage"
        @next-click="nextClick"
        @prev-click="prevClick"
        @current-change="currentChange"
      >
      </el-pagination> -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<style scoped>
.artistic-header {
  font-size: 30px;
  text-align: center;
  color: #ffb7c5;
  padding: 20px 0;
  font-family: "Arial", sans-serif;
  font-weight: bold;
  letter-spacing: 8px; /* 从 2px 增加到 4px */
  text-transform: uppercase;
  background: linear-gradient(to right, #ff9a8b, #ff6b95, #ff9a8b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 2px 2px 4px rgba(255, 107, 149, 0.3);
  animation: shimmer 2s infinite linear;
  position: relative;
}

.artistic-header::before {
  content: attr(data-text);
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  text-shadow: -1px -1px 0 #ffc0cb, 1px -1px 0 #ffc0cb, -1px 1px 0 #ffc0cb,
    1px 1px 0 #ffc0cb;
}

@keyframes shimmer {
  0% {
    background-position: -100% 0;
  }
  100% {
    background-position: 100% 0;
  }
}
.mendian {
  height: 800px;
  background-color: rgb(255, 255, 255);
}
.sj > span {
  margin-right: 20px;
}
.active {
  color: #00ffff;
}
.search {
  width: 500px;
  height: 36px;
  margin-right: 20px;
  margin-bottom: 10px;
  float: left;
}
.date {
  width: 430px;
  height: 36px;
  margin-right: 20px;
  margin-bottom: 10px;
  float: left;
}
.addTo {
  margin: 30px 0 20px;
  width: 150px;
}
.searchInputSize {
  box-sizing: border-box;
  width: 300px;
  height: 36px;
  padding: 0 15px;
}
.searchAndDate {
  margin-top: 15px;
}
.areabox {
  width: 800px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
/**/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
